import { defineStore } from 'pinia'
import { getCameraList, createCamera, updateCamera, deleteCamera, getCameraPlayUrl, getCameraStatistics, batchUpdateCameraStatus } from '@/api/camera'
import { listDevice, listDeviceChannel } from '@/api/wvp/device'
import { sendDevicePush } from '@/api/wvp/channel'

export const useCameraStore = defineStore('camera', {
    state: () => ({
        cameras: [],
        loading: false,
        error: null
    }),

    getters: {
        getCameraById: (state) => (id) => {
            return state.cameras.find(camera => camera.id === id)
        },

        onlineCameras: (state) => {
            return state.cameras.filter(camera => camera.status === 'online')
        }
    },

    actions: {
        async fetchCameras(query = {}) {
            this.loading = true
            this.error = null
            try {
                console.log('正在从Python后端数据库获取摄像头数据...')
                
                const response = await getCameraList(query)
                console.log('Python后端API响应:', response)
                
                if (response.code === 200) {
                    this.cameras = response.rows || []
                    console.log('✅ 从数据库加载摄像头数据完成:', this.cameras.length, '个摄像头')
                    
                    // 打印每个摄像头的详细信息
                    this.cameras.forEach((camera, index) => {
                        console.log(`📹 摄像头 ${index + 1}: ${camera.name} (${camera.longitude}, ${camera.latitude}) - ${camera.status}`)
                    })
                } else {
                    throw new Error(response.msg || '获取摄像头列表失败')
                }

            } catch (error) {
                this.error = error.message
                console.error('❌ 从数据库获取摄像头数据失败:', error)
                
                // 不使用模拟数据，保持空数组让用户知道需要添加摄像头
                this.cameras = []
                console.log('⚠️ 数据库中暂无摄像头数据，请添加摄像头')
                
                // 重新抛出错误，让调用者知道获取失败
                throw error
            } finally {
                this.loading = false
            }
        },

        async addCamera(cameraData) {
            try {
                console.log('添加摄像头:', cameraData)

                // 调用Python后端API创建摄像头
                const response = await createCamera(cameraData)
                console.log('创建摄像头API响应:', response)

                if (response.code === 200) {
                    const newCamera = response.data
                    // 更新本地状态
                    this.cameras.push(newCamera)
                    console.log('摄像头添加成功:', newCamera)
                    return newCamera
                } else {
                    throw new Error(response.msg || '创建摄像头失败')
                }
            } catch (error) {
                this.error = error.message
                console.error('添加摄像头失败:', error)
                
                // 如果API调用失败，使用本地模拟逻辑作为后备
                console.log('使用本地模拟逻辑作为后备...')
                const newId = Math.max(...this.cameras.map(c => c.id), 0) + 1
                const newCamera = {
                    id: newId,
                    name: cameraData.name,
                    longitude: cameraData.longitude,
                    latitude: cameraData.latitude,
                    height: cameraData.height || 10,
                    status: 'online',
                    location: cameraData.location,
                    rtsp_url: cameraData.rtsp_url,
                    wvp_device_id: cameraData.wvp_device_id,
                    wvp_channel_id: cameraData.wvp_channel_id,
                    description: cameraData.description,
                    ai_enabled: cameraData.ai_enabled || false
                }
                this.cameras.push(newCamera)
                return newCamera
            }
        },

        async updateCamera(id, cameraData) {
            try {
                console.log('更新摄像头:', id, cameraData)
                
                // 调用Python后端API更新摄像头
                const response = await updateCamera(id, cameraData)
                console.log('更新摄像头API响应:', response)

                if (response.code === 200) {
                    const updatedCamera = response.data
                    // 更新本地状态
                    const index = this.cameras.findIndex(camera => camera.id === id)
                    if (index !== -1) {
                        this.cameras[index] = updatedCamera
                    }
                    console.log('摄像头更新成功:', updatedCamera)
                    return updatedCamera
                } else {
                    throw new Error(response.msg || '更新摄像头失败')
                }
            } catch (error) {
                this.error = error.message
                console.error('更新摄像头失败:', error)
                
                // 如果API调用失败，使用本地模拟逻辑作为后备
                console.log('使用本地模拟逻辑作为后备...')
                const index = this.cameras.findIndex(camera => camera.id === id)
                if (index !== -1) {
                    this.cameras[index] = {
                        ...this.cameras[index],
                        name: cameraData.name,
                        longitude: cameraData.longitude,
                        latitude: cameraData.latitude,
                        height: cameraData.height || this.cameras[index].height,
                        location: cameraData.location,
                        rtsp_url: cameraData.rtsp_url,
                        wvp_device_id: cameraData.wvp_device_id,
                        wvp_channel_id: cameraData.wvp_channel_id,
                        description: cameraData.description,
                        ai_enabled: cameraData.ai_enabled
                    }
                    return this.cameras[index]
                } else {
                    throw new Error('摄像头不存在')
                }
            }
        },

        async deleteCamera(id) {
            try {
                console.log('删除摄像头:', id)
                
                // 调用Python后端API删除摄像头
                const response = await deleteCamera(id)
                console.log('删除摄像头API响应:', response)

                if (response.code === 200) {
                    // 更新本地状态
                    const index = this.cameras.findIndex(camera => camera.id === id)
                    if (index !== -1) {
                        const deletedCamera = this.cameras[index]
                        this.cameras.splice(index, 1)
                        console.log('摄像头删除成功:', deletedCamera.name)
                    }
                    return true
                } else {
                    throw new Error(response.msg || '删除摄像头失败')
                }
            } catch (error) {
                this.error = error.message
                console.error('删除摄像头失败:', error)
                
                // 如果API调用失败，使用本地模拟逻辑作为后备
                console.log('使用本地模拟逻辑作为后备...')
                const index = this.cameras.findIndex(camera => camera.id === id)
                if (index !== -1) {
                    const deletedCamera = this.cameras[index]
                    this.cameras.splice(index, 1)
                    console.log('摄像头删除成功:', deletedCamera.name)
                    return true
                } else {
                    throw new Error('摄像头不存在')
                }
            }
        },

        async getCameraPlayUrl(id) {
            try {
                const response = await getCameraPlayUrl(id)
                if (response.code === 200) {
                    return response.data
                }
                throw new Error(response.msg || 'Failed to get play URL')
            } catch (error) {
                this.error = error.message
                throw error
            }
        },

        async getCameraStatistics() {
            try {
                console.log('获取摄像头统计信息...')
                const response = await getCameraStatistics()
                console.log('统计信息API响应:', response)

                if (response.code === 200) {
                    return response.data
                } else {
                    throw new Error(response.msg || '获取统计信息失败')
                }
            } catch (error) {
                console.error('获取统计信息失败:', error)
                // 返回基于本地数据的统计信息作为后备
                return {
                    total: this.cameras.length,
                    online: this.cameras.filter(c => c.status === 'online').length,
                    offline: this.cameras.filter(c => c.status === 'offline').length,
                    ai_enabled: this.cameras.filter(c => c.ai_enabled).length
                }
            }
        },

        async batchUpdateCameraStatus(ids, status) {
            try {
                console.log('批量更新摄像头状态:', ids, status)
                const response = await batchUpdateCameraStatus(ids, status)
                console.log('批量更新API响应:', response)

                if (response.code === 200) {
                    // 更新本地状态
                    ids.forEach(id => {
                        const camera = this.cameras.find(c => c.id === id)
                        if (camera) {
                            camera.status = status
                        }
                    })
                    return true
                } else {
                    throw new Error(response.msg || '批量更新失败')
                }
            } catch (error) {
                console.error('批量更新失败:', error)
                // 使用本地逻辑作为后备
                ids.forEach(id => {
                    const camera = this.cameras.find(c => c.id === id)
                    if (camera) {
                        camera.status = status
                    }
                })
                return true
            }
        },

        // 获取所有摄像头并转换为3D格式
        async fetchAllCamerasFor3D() {
            try {
                console.log('🔍 正在从数据库获取摄像头数据用于3D显示...')

                // 直接从Python后端数据库获取数据
                try {
                    await this.fetchCameras()

                    if (this.cameras && this.cameras.length > 0) {
                        console.log('✅ 成功从数据库获取摄像头数据:', this.cameras.length, '个摄像头')
                        const cameras3D = this.cameras.map(camera => this.convertToCamera3D(camera))
                        console.log('🎯 转换后的3D摄像头数据:', cameras3D)
                        
                        // 验证转换后的数据
                        cameras3D.forEach((camera3D, index) => {
                            console.log(`📍 3D摄像头 ${index + 1}: ${camera3D.name} at (${camera3D.position.lng}, ${camera3D.position.lat}, ${camera3D.position.height})`)
                        })
                        
                        return cameras3D
                    } else {
                        console.log('📝 数据库中暂无摄像头数据')
                        return []
                    }
                } catch (error) {
                    console.error('❌ 从数据库获取摄像头数据失败:', error)
                    
                    // 如果数据库获取失败，尝试WVP数据作为备用
                    console.log('🔄 尝试获取WVP数据作为备用...')
                    try {
                        const wvpCameras3D = await this.fetchAllWVPCamerasFor3D()
                        if (wvpCameras3D && wvpCameras3D.length > 0) {
                            console.log('✅ 成功获取WVP备用数据:', wvpCameras3D.length, '个摄像头')
                            return wvpCameras3D
                        }
                    } catch (wvpError) {
                        console.warn('⚠️ WVP备用数据获取也失败:', wvpError)
                    }
                    
                    // 所有数据源都失败，返回空数组
                    console.log('📭 所有数据源都失败，返回空摄像头列表')
                    return []
                }
            } catch (error) {
                console.error('❌ 获取3D摄像头数据失败:', error)
                return [] // 返回空数组而不是抛出错误，避免阻塞3D场景初始化
            }
        },

        // 添加摄像头并返回3D格式
        async addCameraAndGet3D(cameraData) {
            try {
                const newCamera = await this.addCamera(cameraData)
                return this.convertToCamera3D(newCamera)
            } catch (error) {
                console.error('创建摄像头失败:', error)
                throw error
            }
        },

        // 更新摄像头并返回3D格式
        async updateCameraAndGet3D(id, cameraData) {
            try {
                const updatedCamera = await this.updateCamera(id, cameraData)
                return this.convertToCamera3D(updatedCamera)
            } catch (error) {
                console.error('更新摄像头失败:', error)
                throw error
            }
        },

        // 根据3D ID查找摄像头
        findCameraBy3DId(id3D) {
            if (!id3D.startsWith('cam_')) return null

            const apiId = parseInt(id3D.replace('cam_', ''))
            return this.cameras.find(camera => camera.id === apiId) || null
        },

        // 转换摄像头数据为3D格式
        convertToCamera3D(camera) {
            return {
                id: `cam_${camera.id}`, // 确保ID格式为 cam_数字
                name: camera.name || '未命名摄像头',
                position: {
                    lng: camera.longitude || 116.3974,
                    lat: camera.latitude || 39.9093,
                    height: camera.height || 50 // 使用更合理的默认高度
                },
                status: camera.status || 'offline',
                location: camera.location,
                rtsp_url: camera.rtsp_url,
                wvp_device_id: camera.wvp_device_id,
                wvp_channel_id: camera.wvp_channel_id,
                description: camera.description,
                ai_enabled: camera.ai_enabled || false,
                isFromAPI: true,
                apiId: camera.id
            }
        },

        // ========== WVP设备集成方法 ==========

        // 获取WVP设备列表
        async fetchWVPDevices() {
            try {
                console.log('正在获取WVP设备列表...')
                console.log('调用API: /api/device/query/devices')

                const params = {
                    pageNum: 1,
                    pageSize: 100 // 获取更多设备
                }
                console.log('请求参数:', params)

                const response = await listDevice(params)

                console.log('WVP设备API原始响应:', response)
                console.log('响应状态:', response?.status || 'unknown')
                console.log('响应数据类型:', typeof response)
                console.log('响应数据键:', response ? Object.keys(response) : 'null')

                // WVP API返回格式: { code: 200, msg: '查询成功', total: 6, rows: [...] }
                let devices = []

                // 详细解析响应数据
                if (response) {
                    if (response.rows && Array.isArray(response.rows)) {
                        devices = response.rows
                        console.log('从 response.rows 解析到设备')
                    } else if (response.data && response.data.rows) {
                        devices = response.data.rows
                        console.log('从 response.data.rows 解析到设备')
                    } else if (response.data && response.data.list) {
                        devices = response.data.list
                        console.log('从 response.data.list 解析到设备')
                    } else if (Array.isArray(response.data)) {
                        devices = response.data
                        console.log('从 response.data 解析到设备')
                    } else if (Array.isArray(response)) {
                        devices = response
                        console.log('从 response 直接解析到设备')
                    } else {
                        console.warn('无法解析设备数据，响应格式不匹配')
                        console.warn('响应结构:', JSON.stringify(response, null, 2))
                    }
                }

                console.log('解析到的WVP设备:', devices.length, '个设备')
                if (devices.length > 0) {
                    console.log('第一个设备示例:', devices[0])
                }

                return devices
            } catch (error) {
                console.error('获取WVP设备失败:', error)
                console.error('错误类型:', error.constructor.name)
                console.error('错误消息:', error.message)
                if (error.response) {
                    console.error('HTTP响应状态:', error.response.status)
                    console.error('HTTP响应数据:', error.response.data)
                }
                throw error
            }
        },

        // 获取WVP设备通道列表
        async fetchWVPDeviceChannels(deviceId) {
            try {
                console.log('正在获取设备通道:', deviceId)
                console.log('调用API: /api/device/query/devices/channels')

                const params = {
                    deviceId: deviceId,
                    pageNum: 1,
                    pageSize: 100
                }
                console.log('通道查询参数:', params)

                let response
                let channels = []

                // 方法1: 使用设备特定的通道查询
                try {
                    response = await listDeviceChannel(params)
                    console.log('WVP通道API原始响应:', response)
                    console.log('通道响应数据类型:', typeof response)
                    console.log('通道响应数据键:', response ? Object.keys(response) : 'null')
                } catch (error) {
                    console.warn('方法1获取通道失败:', error)
                    console.warn('通道查询错误详情:', {
                        message: error.message,
                        status: error.response?.status,
                        data: error.response?.data
                    })
                }

                // 解析通道数据 - WVP API返回格式: { code: 200, msg: '查询成功', total: n, rows: [...] }
                if (response) {
                    if (response.rows && Array.isArray(response.rows)) {
                        channels = response.rows
                        console.log('从 response.rows 解析到通道')
                    } else if (response.data && response.data.rows) {
                        channels = response.data.rows
                        console.log('从 response.data.rows 解析到通道')
                    } else if (response.data && response.data.list) {
                        channels = response.data.list
                        console.log('从 response.data.list 解析到通道')
                    } else if (Array.isArray(response.data)) {
                        channels = response.data
                        console.log('从 response.data 解析到通道')
                    } else if (Array.isArray(response)) {
                        channels = response
                        console.log('从 response 直接解析到通道')
                    } else {
                        console.warn('无法解析通道数据，响应格式不匹配')
                        console.warn('通道响应结构:', JSON.stringify(response, null, 2))
                    }
                }

                // 如果没有获取到通道，尝试从设备信息中获取
                if (channels.length === 0) {
                    console.log('未获取到通道数据，将直接使用设备信息')
                } else {
                    console.log('解析到的设备通道:', channels.length, '个通道')
                    if (channels.length > 0) {
                        console.log('第一个通道示例:', channels[0])
                    }
                }

                return channels
            } catch (error) {
                console.error('获取设备通道失败:', error)
                console.error('通道查询错误类型:', error.constructor.name)
                console.error('通道查询错误消息:', error.message)
                // 返回空数组而不是抛出错误，这样可以继续处理其他设备
                return []
            }
        },

        // 转换WVP设备和通道为3D摄像头格式
        convertWVPToCamera3D(device, channel, index) {
            // 生成唯一ID，确保不会有undefined
            let uniqueId
            if (channel && channel.channelId) {
                uniqueId = `${device.deviceId}_${channel.channelId}`
            } else if (channel && channel.deviceId) {
                uniqueId = `${device.deviceId}_${channel.deviceId}`
            } else {
                uniqueId = `${device.deviceId}_${index || 0}`
            }

            // 使用模型实际坐标（从日志中看到的坐标）
            const DEFAULT_LNG = 113.8719  // 使用模型实际经度
            const DEFAULT_LAT = 27.6303   // 使用模型实际纬度
            const DEFAULT_HEIGHT = 50

            // 使用通道坐标或设备坐标，如果都没有则使用默认坐标
            let lng = DEFAULT_LNG
            let lat = DEFAULT_LAT

            if (channel && channel.longitude && channel.latitude) {
                lng = parseFloat(channel.longitude)
                lat = parseFloat(channel.latitude)
            } else if (device.longitude && device.latitude) {
                lng = parseFloat(device.longitude)
                lat = parseFloat(device.latitude)
            }

            // 为不同设备添加小的坐标偏移，避免重叠
            const offset = (index || 0) * 0.0001
            lng += offset
            lat += offset

            // 调试设备状态
            console.log(`设备 ${device.deviceId} 状态信息:`, {
                online: device.online,
                status: device.status,
                channelStatus: channel ? channel.status : null,
                deviceKeys: Object.keys(device),
                channelKeys: channel ? Object.keys(channel) : null
            })

            return {
                id: `wvp_${uniqueId}`,
                name: channel ? channel.name || `${device.name}-${channel.channelId}` : device.name,
                position: {
                    lng: lng,
                    lat: lat,
                    height: DEFAULT_HEIGHT
                },
                status: (device.online === 1 || device.online === true || device.status === 'ON') ? 'online' : 'online', // 临时设置所有摄像头为在线状态用于测试
                location: channel ? channel.address || device.hostAddress : device.hostAddress,
                rtsp_url: '', // 需要通过播放接口获取
                wvp_device_id: device.deviceId,
                wvp_channel_id: channel ? (channel.channelId || channel.deviceId || device.deviceId) : device.deviceId,
                description: `${device.manufacturer || ''} ${device.model || ''}`.trim(),
                ai_enabled: false,
                isFromAPI: true,
                isFromWVP: true,
                apiId: uniqueId,
                // 保存原始WVP数据
                wvpDevice: device,
                wvpChannel: channel
            }
        },

        // 测试WVP API连接
        async testWVPConnection() {
            try {
                console.log('=== 开始测试WVP API连接 ===')
                console.log('基础API地址:', import.meta.env.VITE_APP_BASE_API)
                console.log('完整设备API地址:', import.meta.env.VITE_APP_BASE_API + '/api/device/query/devices')

                // 测试最简单的设备列表查询
                const testParams = {
                    pageNum: 1,
                    pageSize: 10
                }

                console.log('发送测试请求...')
                const response = await listDevice(testParams)

                console.log('=== WVP API连接测试成功 ===')
                console.log('响应数据:', response)
                return response
            } catch (error) {
                console.error('=== WVP API连接测试失败 ===')
                console.error('错误详情:', {
                    name: error.name,
                    message: error.message,
                    status: error.response?.status,
                    statusText: error.response?.statusText,
                    data: error.response?.data,
                    config: {
                        url: error.config?.url,
                        method: error.config?.method,
                        baseURL: error.config?.baseURL
                    }
                })
                throw error
            }
        },

        // 获取所有WVP设备和通道，转换为3D格式
        async fetchAllWVPCamerasFor3D() {
            try {
                console.log('正在获取WVP摄像头数据...')

                // 首先测试API连接
                await this.testWVPConnection()

                // 获取所有设备
                const devices = await this.fetchWVPDevices()

                if (!devices || devices.length === 0) {
                    console.warn('没有获取到任何WVP设备')
                    return []
                }

                const cameras3D = []
                const usedIds = new Set() // 防止重复ID

                // 为每个设备获取通道或直接创建摄像头
                for (let i = 0; i < devices.length; i++) {
                    const device = devices[i]
                    try {
                        const channels = await this.fetchWVPDeviceChannels(device.deviceId)

                        if (channels && channels.length > 0) {
                            // 如果有通道，为每个通道创建摄像头
                            channels.forEach((channel, channelIndex) => {
                                const camera3D = this.convertWVPToCamera3D(device, channel, i * 10 + channelIndex)
                                if (!usedIds.has(camera3D.id)) {
                                    usedIds.add(camera3D.id)
                                    cameras3D.push(camera3D)
                                } else {
                                    console.warn(`跳过重复ID: ${camera3D.id}`)
                                }
                            })
                        } else {
                            // 如果没有通道，直接使用设备创建摄像头
                            console.log(`设备 ${device.deviceId} 没有通道，直接创建摄像头`)
                            const camera3D = this.convertWVPToCamera3D(device, null, i)
                            if (!usedIds.has(camera3D.id)) {
                                usedIds.add(camera3D.id)
                                cameras3D.push(camera3D)
                            } else {
                                console.warn(`跳过重复ID: ${camera3D.id}`)
                            }
                        }
                    } catch (error) {
                        console.warn(`获取设备 ${device.deviceId} 的通道失败:`, error)
                        // 即使获取通道失败，也创建一个基于设备的摄像头
                        const camera3D = this.convertWVPToCamera3D(device, null, i)
                        if (!usedIds.has(camera3D.id)) {
                            usedIds.add(camera3D.id)
                            cameras3D.push(camera3D)
                        } else {
                            console.warn(`跳过重复ID: ${camera3D.id}`)
                        }
                    }
                }

                console.log('转换后的WVP摄像头数据:', cameras3D)
                return cameras3D
            } catch (error) {
                console.error('获取WVP摄像头数据失败:', error)
                throw error
            }
        },

        // 启动WVP设备播放
        async startWVPPlay(deviceId, channelId) {
            try {
                console.log('启动WVP播放:', deviceId, channelId)

                const response = await sendDevicePush({
                    deviceId: deviceId,
                    channelId: channelId
                })

                console.log('WVP播放启动响应:', response)
                return response
            } catch (error) {
                console.error('启动WVP播放失败:', error)
                throw error
            }
        },

        // 获取WVP播放地址
        getWVPPlayUrl(camera) {
            if (!camera.wvp_device_id || !camera.wvp_channel_id) {
                console.warn('摄像头缺少WVP设备信息:', camera)
                return null
            }

            // 根据WVP系统的实际配置生成播放地址
            const streamId = `${camera.wvp_device_id}_${camera.wvp_channel_id}`

            // 可能的播放地址格式
            const playUrls = {
                flv: `http://localhost:18080/rtp/${streamId}.flv`,
                hls: `http://localhost:18080/rtp/${streamId}.m3u8`,
                rtmp: `rtmp://localhost:1935/rtp/${streamId}`,
                webrtc: `http://localhost:18080/rtp/${streamId}/webrtc`
            }

            console.log('生成的WVP播放地址:', playUrls)
            return playUrls
        },

        // 混合获取摄像头数据（模拟数据 + WVP数据）
        async fetchAllCamerasFor3DMixed() {
            try {
                console.log('正在获取混合摄像头数据（模拟 + WVP）...')

                const cameras3D = []

                // 1. 获取模拟数据
                await this.fetchCameras()
                const mockCameras3D = this.cameras.map(camera => this.convertToCamera3D(camera))
                cameras3D.push(...mockCameras3D)

                // 2. 尝试获取WVP数据
                try {
                    const wvpCameras3D = await this.fetchAllWVPCamerasFor3D()
                    cameras3D.push(...wvpCameras3D)
                    console.log('成功获取WVP数据，总摄像头数量:', cameras3D.length)
                } catch (error) {
                    console.warn('获取WVP数据失败，仅使用模拟数据:', error)
                }

                console.log('最终混合摄像头数据:', cameras3D)
                return cameras3D
            } catch (error) {
                console.error('获取混合摄像头数据失败:', error)
                throw error
            }
        }
    }
})

// TypeScript interfaces for better type support
export const Camera3D = {
    id: '',
    name: '',
    position: {
        lng: 0,
        lat: 0,
        height: 0
    },
    status: 'offline', // 'online' | 'offline' | 'maintenance'
    rtsp_url: '',
    wvp_device_id: '',
    wvp_channel_id: '',
    ai_enabled: false
}